package cn.com.sparkle.paxos.net.factory.raptor;

import org.apache.log4j.Logger;

import cn.com.sparkle.paxos.iomodel.protobuffmessage.PaxosMessages.MessagePackage;
import cn.com.sparkle.paxos.net.factory.NetHandler;
import cn.com.sparkle.raptor.core.protocol.MultiThreadProtecolHandler.ProtocolHandlerIoSession;
import cn.com.sparkle.raptor.core.protocol.ProtocolHandler;
import cn.com.sparkle.raptor.core.transport.socket.nio.IoSession;

public class RaptorHandler implements ProtocolHandler{
	private final static Logger logger = Logger.getLogger(RaptorHandler.class);
	public NetHandler netHandler;
	public RaptorHandler(NetHandler netHandler){
		this.netHandler = netHandler;
	}
	@Override
	public void onOneThreadSessionOpen(ProtocolHandlerIoSession session) {
		RaptorPaxosSession rps = new RaptorPaxosSession(session);
		rps.attach(session.customAttachment);
		session.customAttachment = rps;
		netHandler.onConnect(rps);
	}

	@Override
	public void onOneThreadSessionClose(ProtocolHandlerIoSession session) {
		RaptorPaxosSession rps = (RaptorPaxosSession)session.customAttachment;
		netHandler.onDisconnect(rps);
	}

	@Override
	public void onOneThreadCatchException(IoSession ioSession,
			ProtocolHandlerIoSession attachment, Throwable e) {
		if(attachment == null){
			netHandler.onRefuse(ioSession.attachment());
		}
		logger.error("", e);
	}

	@Override
	public void onOneThreadMessageRecieved(Object receiveObject,
			ProtocolHandlerIoSession session) {
		RaptorPaxosSession rps = (RaptorPaxosSession)session.customAttachment;
		netHandler.onRecieve(rps, (MessagePackage)receiveObject);
	}

	@Override
	public void onOneThreadMessageSent(ProtocolHandlerIoSession session,
			int sendSize) {
//		nothing to do 
	}

}
